<?php 
namespace app\mall\controller;
use app\mall\controller\Base;
use service\DataService;
use think\Db;
use think\Request;
use app\mall\model\GoodsCategory;
use app\mall\model\Goods as GoodsModel;
use app\mall\service\GoodsService;
use app\mall\model\GoodsSpec;
use app\mall\model\GoodsSpecDetail;
use app\comm\service\GoodsService as GoodsServ;
class Goods2 extends Base{
    public $table = 'GoodsSpecName';
	/**
	 * 商品分类
	 * @return [type] [description]
	 */
 	public function category(){
 		$this->title = '商品分类';
        $get = $this->request->get();
        $db = Db::name('goods_category')->where('pid',0);
        foreach (['title'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }
        $yangshi = config("qiniu");
        $this->assign('yangshi',$yangshi['yangshi']);          //七牛样式后缀
        return parent::_list($db);
 	}	
    /**
     * 子级分类
     * @return [type] [description]
     */
    public function child_category(){
        $this->title = '商品分类';
        $id = input('id');
        $db = Db::name('goods_category')->where('pid',$id);
        $yangshi = config('qiniu');
        $this->assign('yangshi',$yangshi['yangshi']);
        return parent::_list($db);
    }

    /**
     * 添加 -- 编辑门店
     */
    public function add_category(){
        $categoryservice = new GoodsService();      //商品服务层
        if(request()->isPost()){
            $post = input('post.');
            if(empty($post['id'])){     //添加
                $categoryservice->add_category($post);
            }else{
                $categoryservice->edit_category($post,$post['id']);
            }
        }else{
            $id = input('id');
            if(empty($id)){
                $list = GoodsCategory::all(['status'=>1,'pid'=>0]);
                $this->assign('list',$list);
            }else{
                $list = Db::name('goods_category')->where('status',1)->where('pid',0)->where('id','neq',$id)->select();
                $this->assign('list',$list);
            }
            $vo = GoodsCategory::get(['id'=>$id]);
            $yangshi = config('qiniu');
            $this->assign('yangshi',$yangshi);          //七牛云图片压缩样式
            $this->assign('vo',$vo);
            return $this->fetch('add_category');
        }
    }
    /**
     * 删除分类
     * @return [type] [description]
     */
    public function del_category(){
        $id = input('id');
        $GoodsCategory = new GoodsCategory();      //商品服务层
        $res = $GoodsCategory->del($id);
        $res['code'] == 1?$this->success('删除成功',''):$this->error($res['msg'],'');
    }
    /**
     * 商品列表
     * @return [type] [description]
     */
    public function goods(){
        $this->title = '商品列表';
        $get = request()->get();
        $map = array();
        $map['a.is_deleted'] = array('eq',0);
        if(!empty($get['name'])){
            $map['a.name'] = array('like',"%".$get['name']."%");
        }
        $rows = intval(request()->get('rows', cookie('rows')));
        cookie('rows', $rows >= 10 ? $rows : 20);
        $page = Db::name('goods')->alias('a')->join('ys_goods_category b','a.cat_id=b.id','LEFT')->where($map)->field('a.*,b.title')->order('id desc')->paginate($rows, false, ['query' => request()->get('', '', 'urlencode')]);
        list($pattern, $replacement) = [['|href="(.*?)"|', '|pagination|'], ['data-open="$1"', 'pagination pull-right']];
        list($result['list'], $result['page']) = [$page->all(), preg_replace($pattern, $replacement, $page->render())]; 
        $yangshi = config("qiniu");
        $this->assign('yangshi',$yangshi['yangshi']);          //七牛样式后缀
        $this->assign('title',$this->title);
        return $this->fetch('goods',$result);
    }
    /**
     * 添加 -- 编辑商品
     */
    public function add_goods(){
        if(request()->isPost()){
            $GoodsModel = new GoodsModel();      //商品模型
            $post = input('post.');
            $post['addtime'] = time();
            $post['logo'] = trim($post['logo']);        //去掉两端空格
            $result = $GoodsModel->add_edit($post);
            if(($result['code'] == 1) && !empty($post['spec_id'])){
                $spec = $this->spec_group($post,$result['goods_id']);   
                foreach($spec as $k => $v){     //循环保存记录
                    $model = new GoodsSpec();
                    $goodsspecdetailmodel = new GoodsSpecDetail();
                    if(isset($v['id'])){
                        $kid = $spec[$k]['id'];
                        unset($spec[$k]['id']);
                        $res = Db::name('goods_spec')->where('id',$kid)->update($spec[$k]);
                    }else{
                        $res = $model->save($spec[$k]);
                    }   
                    // $res = $model->save($spec[$k]);
                    // file_put_contents('log.txt',$model->id."<br/>",FILE_APPEND);
                    if($res!=false){
                        if(isset($post['spec_detail_id'])){        //更新
                            $data = array('goods_id'=>$result['goods_id'],'title'=>'尺寸: '.$v['detail'],'price'=>$post['jiage'][$k],'score'=>$post['jifen'][$k],'specs'=>$post['detail_specs'][$k],'recipe_ratio'=>$post['recipe_ratio'][$k]);
                            $res = Db::name('goods_spec_detail')->where('id',$post['spec_detail_id'][$k])->update($data);
                            // halt($post['spec_detail_id'][$k]);
                        }else{          //新增
                            $data = array('goods_id'=>$result['goods_id'],'title'=>'尺寸: '.$v['detail'],'price'=>$post['jiage'][$k],'score'=>$post['jifen'][$k],'specs'=>$model->id,'recipe_ratio'=>$post['recipe_ratio'][$k],'is_deleted'=>0,'addtime'=>time());
                            $res = $goodsspecdetailmodel->save($data);
                        }
                    }else{
                        $result['code'] = 0;
                    }
                }
                // $res = $model->saveall($spec);
                // if($res!=false){        //保存商品属性详情
                //     $psec_detail = $this->spec_detail($post,$result['goods_id']);
                //     $specdetailmodel = new GoodsSpecDetail();
                //     $res = $specdetailmodel->saveall($psec_detail);
                // }
                // $res>0?$result['code'] = 1:$result['code'] = 0;
                Db::name('goods')->where('id',$result['goods_id'])->update(['is_spec'=>1]);     //更新商品有属性状态
            }
            $result['code'] == 1?$this->success('保存成功',''):$this->error($result['msg'],'');
        }
        $id = input('id');
        $vo = Db::name('goods')->where('id',$id)->find();
        $list = Db::name('goods_category')->where('status',1)->select();      //商品分类
        $shuxing = Db::name('goods_spec')->alias('a')->join('ys_goods_spec_detail b','a.id=b.specs','LEFT')->where('a.goods_id',$id)->field('a.spec_id,a.goods_id,a.id,a.detail,b.title,b.price,b.score,b.id as spec_detail_id,b.specs,b.recipe_ratio')->select();
        // halt($shuxing);
        $spec = Db::name('goods_spec_name')->select();
        $this->assign('shuxing',$shuxing);
        $this->assign('list',$list);
        $this->assign('spec',$spec);            //商品属性名称
        $this->assign('vo',$vo);
        $this->assign('title','编辑商品');
        if(empty($id)){
            return $this->fetch('add_goods');
        }else{
            return $this->fetch('edit_goods');
        }
    }
    /**
     * 商品 -- 上架
     */
    public function on_sall(){
        $table = 'Goods';
        if (DataService::update($table)) {
            $this->success("上架成功", '');
        }
        $this->error("上架失败，请稍候再试！");
    }
    /**
     * 商品 -- 下架
     * @return [type] [description]
     */
    public function down_sall(){
        if (DataService::update($table)) {
            $this->success("下架成功", '');
        }
        $this->error("下架失败，请稍候再试！");
    }

    /**
     * 红包列表
     * @return [type] [description]
     */
    public function coupon(){

    }
    /**
     * 添加优惠券
     */
    public function add_coupon(){
        $goods_id = input('id');
        if(request()->isPost()){
            $data = input('post.');
        }
        $this->assign('goods_id',$goods_id);
        return $this->fetch('add_coupon');
    }
    /**
     * 删除商品属性
     * @return [type] [description]
     */
    public function del_spec(){
        $id = input('id');
        $res = Db::name('goods_spec')->delete(['id'=>$id]);
        $res>0?$this->success('删除成功',''):$this->error('删除失败','');
    }
    /**
     * 删除
     * @return [type] [description]
     */
    public function del_goods(){
        $table = "Goods";
        if (DataService::update($table)) {
            $this->success("删除成功！", '');
        }
        $this->error("删除失败，请稍候再试！");
    }
    /**
     * 编辑商品属性
     * @return [type] [ ]
     */
    public function goods_spec_name(){
        $this->title = '商品属性';
        $get = $this->request->get();
        $db = Db::name('goods_spec_name')->where(['is_deleted' => '0']);
        foreach (['name'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }
        return parent::_list($db);
    }
    /**
     * 编辑商品属性
     */
    public function add_goods_spec_name(){
        $this->assign('time',time());       //添加的时间
        return $this->_form('GoodsSpecName', 'add_goods_spec_name','id');        //保存数据
    }
    /**
     * 删除商品属性名称
     * @return [type] [description]
     */
    public function del_goods_spec_name(){
        $table = "GoodsSpecName";
        if (DataService::update($table)) {
            $this->success("用户删除成功！", '');
        }
        $this->error("用户删除失败，请稍候再试！");
    }

    /**
     * 商品评论操作
     * @yunhaiyidao
     */
    public function comment(){
        $GoodsServ =  new GoodsServ();
        $urlend = $this->request->get('', '', 'urlencode');
        $get = $this->request->get();
        if(array_key_exists('name', $get)){
            $name = $get['name'];
        }else{
            $name='';
        }
        $page = $GoodsServ ->litbioa($urlend,$name);
        list($pattern, $replacement) = [['|href="(.*?)"|', '|pagination|'], ['data-open="$1"', 'pagination pull-right']];
        list($result['list'], $result['page']) = [$page->all(), preg_replace($pattern, $replacement, $page->render())];
        !empty($this->title) && $this->assign('title', $this->title);
        $yangshi = config("qiniu");
        $this->assign('yangshi',$yangshi['yangshi']); 
        return $this->fetch('', $result);
    }
    /**
     * 商品品论操作
     * @yunhaiyidao
     */
    public function comment_shows($id){
        $goodserv =  new GoodsServ($id);
        if($goodserv->ishowsLook($id)){
            $this->success('已经隐藏成功!', ''); 
        }
        $this->success('已经隐藏成功!', ''); 
    }
    /**
     * 商品品论详情
     * @yunhaiyidao
     */
    public function comment_detail($goodid){
        return $this->fetch('', $result);     
    }
    /**
     * 添加商品属性
     * dikaer()字符串   dikaerr数组
     */
    // public function add_goods_spec(){
    //     if(request()->isPost()){
    //         $post = input('post.');     //接受的数据
    //         $da = $this->spec_group($post,$post['id']);
    //         $goodsspecmodel = new GoodsSpec();
    //         if(!empty($da)){
    //             $res = $goodsspecmodel->saveall($da);
    //             if($res>0){
    //                 $this->redirect('create_goods_spec',array('id'=>$post['id']));      //跳转生成商品属性
    //                 // $this->success('成功','');
    //                 // $result['code'] = 1;
    //             }else{
    //                 $this->error('规格生成失败','');
    //                 // $result['code'] = 0;
    //             }  
    //         }
    //     }else{
    //         $id = input('id');      //商品id
    //         $spec_cate = Db::name('goods_spec_name')->field('id,name')->select();        //属性分类名称
    //         $this->assign('spec_cate',$spec_cate);
    //         $this->assign('id',$id);
    //         $this->assign('title','添加商品属性');
    //         return $this->fetch('add_goods_spec');
    //     }
    // }  
    /**
     * 生成商品属性
     * 组合生成一个隐藏域，进行属性的编辑
     * @return [type] [description]
     */
    // public function create_goods_spec(){
    //     if(request()->isPost()){
    //         $post = input('post.');
    //         $model = new GoodsSpecDetail();
    //         $specs = $this->spec_arr($post,$post['goods_id']);
    //         $res = $model->saveall($specs);
    //         $res>0?$this->success('保存成功',''):$this->error('保存失败','');
    //     }else{
    //         $goods_id = input('id');
    //         // $count = Db::name('goods_spec_detail')->where(['goods_id'=>$goods_id,'is_deleted'=>0])->select();       //查看配方的属性
    //         $spec = Db::name('goods_spec')->alias('a')->join('ys_goods_spec_name b','a.spec_id=b.id','LEFT')->where('a.goods_id',$goods_id)->field('a.id,a.detail,a.spec_id,b.name')->select();      //属性的详情
    //         foreach($spec as $k => $v){
    //             $spec_arr[$v['spec_id']][] = $v['id'];                  //属性id数组
    //             $spec_name[$v['spec_id']][] = $v['name'].": ".$v['detail'];             //属性名称数组
    //         }
    //         $spec_names = dikaerr($spec_name);      //组合属性名称数组
    //         $spec_res = array();    
    //         foreach($spec_names as $kk => $vv){
    //             $spec_res[$kk][0] = implode(" ",$spec_names[$kk]);
    //         }
    //         $spec_arrs  = dikaer($spec_arr);         //组合属性id字符串
    //         foreach($spec_res as $k1 => $v1){
    //             $spec_res[$k1]['specs'] = $spec_arrs[$k1];
    //             $spec_res[$k1]['price'] = Db::name('goods_spec_detail')->where('specs',$spec_arrs[$k1])->value('price');
    //             $spec_res[$k1]['id'] = Db::name('goods_spec_detail')->where('specs',$spec_arrs[$k1])->value('id');
    //             $spec_res[$k1]['recipe_ratio'] = Db::name('goods_spec_detail')->where('specs',$spec_arrs[$k1])->value('recipe_ratio');
    //         }
    //         $this->assign('goods_id',$goods_id);
    //         $this->assign('spec_res',$spec_res);            //模板渲染数据
    //         $this->assign('title','商品属性');
    //         return $this->fetch('create_goods_spec');
    //     }
    // }
    /**
     * 单个商品属性的组合
     * @return [type] [description]
     */
    // public function group_goods_spec(){
    //     if(request()->isPost()){
    //         $post = input('post.');
    //         $goodspecmodel = new GoodsSpec();
    //         $model = new GoodsSpecDetail();
    //         $specs = $this->signal_goods_arr($post,$post['goods_id']);
    //         // halt($specs);
    //         $res = $goodspecmodel->saveall($specs[0]);
    //         $res = $model->saveall($specs[1]);
    //         $res>0?$this->success('保存成功',''):$this->error('保存失败','');
    //     }else{
    //         $goods_id = input('id');
    //         $spec_id = Db::name('goods')->where('id',$goods_id)->value('goods_spec');           //商品的限制住的属性分类请先
    //         if(!$spec_id){
    //             $this->error('该商品没有添加规格，请先添加规格','');
    //         }
    //         $spec_name = Db::name('goods_spec_name')->where('id',$spec_id)->field('id,name,addtime')->find();      //属性分类名称
    //         $spec = Db::name('goods_detail')->alias('a')->join('ys_goods_spec_name b','a.specs=b.id','LEFT')->where('goods_id',$goods_id)->field('a.')->select();
    //         $this->assign('goods_id',$goods_id);
    //         $this->assign('spec_name',$spec_name);            //模板渲染数据
    //         $this->assign('title','商品属性');
    //         return $this->fetch('group_goods_spec');
    //     }
    // }
    // /**
    //  * 商品单属性分类
    //  * @return [type] [description]
    //  */
    // private function signal_goods_arr($data,$goods_id){
    //     $price = $data['price'];
    //     $detail = $data['detail'];
    //     $recipe_ratio = $data['recipe_ratio'];
    //     foreach($price as $k => $v){
    //         $arr1[$k]['spec_id'] = $data['spec_id'];     //goods_spec表
    //         $arr1[$k]['goods_id'] = $goods_id;
    //         $arr1[$k]['detail'] = $detail[$k];
    //         $arr1[$k]['addtime'] = time();
    //         $arr2[$k]['goods_id'] = $goods_id;              //goods_spec_detail表    
    //         $arr2[$k]['price'] = $v;
    //         $arr2[$k]['specs'] = $data['spec_id'];
    //         $arr2[$k]['addtime'] = time();
    //         $arr2[$k]['recipe_ratio'] = $recipe_ratio[$k];
    //     }
    //     $da[0] = $arr1;  
    //     $da[1] = $arr2;
    //     return $da;
    // }
    /**
     * 添加属性是进行输出
     * @return [type] [description]
     */
    private function spec_group($data,$goods_id){
        $spec_id = $data['spec_id'];            //商品属性ID
        $spec = $data['details'];          //商品属性名称
        foreach($spec_id as $k => $v){
            if(!empty($data['sid'])){
                $res[$k]['id'] = $data['sid'][$k];
            }
            $res[$k]['spec_id'] = $v;
            $res[$k]['goods_id'] = $goods_id;
            $res[$k]['detail'] = $spec[$k];
            $res[$k]['addtime'] = time();
        }
        return $res;
    }
    /**
     * 保存商品属性详情
     * @Author   lingyun
     * @DateTime 2017-11-27T11:45:07+0800
     * @return   [type]                   [description]
     */ 
    private function spec_detail($data,$goods_id){
        $title = $data['details'];      //属性标题
        $price = $data['jiage'];
        $score = $data['jifen'];
        $specs = $data['spec_id'];
        $recipe_ratio = $data['recipe_ratio'];
        foreach($score as $k => $v){
            if(!empty($data['spec_id'])){
                $spec[$k]['id'] = $data['spec_id'][$k];
            }
            if(!empty($data['specs'])){
                $spec[$k]['specs'] = $data['specs'][$k];
            }
            $spec[$k]['goods_id'] = $goods_id;
            $spec[$k]['title'] = '尺寸: '.$title[$k];
            $spec[$k]['price'] = $price[$k];
            $spec[$k]['score'] = $v;
            $spec[$k]['specs'] = $specs[$k];
            $spec[$k]['recipe_ratio'] = $recipe_ratio[$k];
            $spec[$k]['is_deleted'] = 0;
            $spec[$k]['addtime'] = time();
        }
        return $spec;
    }
    // /**
    //  * 构造商品属性数组数据
    //  * @param  [type] $data     接受的数据
    //  * @param  [type] $goods_id 商品ID
    //  * @return [type]           返回入库的数据
    //  */
    // private function spec_arr($data,$goods_id){
    //     $specs = $data['specs'];       //属性id
    //     if(isset($data['price'])){
    //         $price = $data['price'];        //价格
    //     }
    //     if(isset($data['recipe_ratio'])){
    //         $recipe = $data['recipe_ratio'];    //配方比例
    //     }
    //     if(isset($data['id'])){
    //         $id = $data['id'];
    //     }
    //     $title = $data['title'];        //属性的标题
    //     $score = $data['score'];        //商品积分
    //     foreach($specs as $k => $v){
    //         $spec[$k]['specs'] = $v;
    //         $spec[$k]['title'] = $title[$k];
    //         $spec[$k]['goods_id'] = $goods_id;
    //         if(isset($price[$k])){
    //             $spec[$k]['price'] = $price[$k];
    //         }
    //         if(isset($resipe[$k])){
    //             $spec[$k]['recipe_ratio'] = $recipe[$k];
    //         }
    //         if(isset($score[$k])){
    //             $spec[$k]['score'] = $score[$k];
    //         }
    //         if(isset($id[$k])){
    //             $spec[$k]['id'] = $id[$k];
    //         }
    //         $spec[$k]['addtime'] = time();
    //     }
    //     return $spec;           //返回入库数据
    // }

}

?>